<?php
$database = "db";
$Tables_in = "Tables_in_".$database;

function writeFile($data){
        $fpt = fopen('schema.sql','a');
        fwrite($fpt,$data);
        fwrite($fpt,"\n");
}  

function dumpData($table){
	$result = mysql_query("SELECT * FROM $table");
	$i=0;
	$n = mysql_num_rows($result);
	while($obj = mysql_fetch_array($result)){
		$b = "INSERT INTO $table VALUES (";
		for($j=0;$j<sizeof($obj)/2;$j++){			
				$b.="'".addslashes($obj[$j])."',";			
		}
		$b = substr($b,0,strlen($b)-1);
		//echo "<br />".$b;
		$b.=");";
		writeFile($b);
	}
}

mysql_connect("localhost","root","");
@mysql_select_db($database) or die( "Unable to select database");

$result = mysql_query("show tables") or die(mysql_error());

while($obj = mysql_fetch_object($result)){
        writeFile('CREATE TABLE IF NOT EXISTS `'.$obj->$Tables_in.'` (');
        $tables = mysql_query("describe ".$obj->$Tables_in) or die(mysql_error());
		
		$n = mysql_num_rows($tables);
		$i=0;	
		
        while($describe = mysql_fetch_object($tables)){
                $Type = explode('(',$describe->Type);
                $size = substr($Type[1], 0, strlen($Type[1])-1);               
				if($size == ''){
					if($i!=$n-1)
						writeFile('`'.$describe->Field.'` '.$Type[0].' default NULL,');
					else
						writeFile('`'.$describe->Field.'` '.$Type[0].' default NULL');
				}else{
					if($i!=$n-1)
						writeFile('`'.$describe->Field.'` '.$Type[0].'('.$size.') default NULL,');
					else
						writeFile('`'.$describe->Field.'` '.$Type[0].'('.$size.') default NULL');
				}
                if($describe->Key!=''){
                        if($describe->Key=='PRI'){
                                if($size == ''){
									if($i!=$n-1)
                                        writeFile('PRIMARY KEY  (`'.$describe->Field.'`),');
									else
										writeFile('PRIMARY KEY  (`'.$describe->Field.'`)');
                                }
                        }
                }
			$i++;	       
        }
        writeFile(') ENGINE=MyISAM  DEFAULT CHARSET=latin1;');
		dumpData($obj->$Tables_in);
}
?>
